/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

/**
 *
 * @author Administrator
 */
import java.awt.Desktop;
import java.io.*;

public class FileExtensions {

    public static String[] getFileNameAndExtension(String fileName) {
        File tmpFile = new File(fileName);
        tmpFile.getName();
        int whereDot = tmpFile.getName().lastIndexOf('.');
        if (0 < whereDot) {
            return new String[]{tmpFile.getName().substring(0, whereDot), tmpFile.getName().substring(whereDot)};
        }
        return new String[]{tmpFile.getName(), ""};
    }

    public static String getFileExtension(String fileName) {
        return getFileNameAndExtension(fileName)[1];
    }

    public static String getFileNameWithoutExtension(String fileName) {
        return getFileNameAndExtension(fileName)[0];
    }

    public static String getSimilarNonExistentFile(String filename) throws IOException {
        File fileInfo = new File(filename);
        File dirInfo = new File(fileInfo.getParent());
        if (fileInfo.exists()) {
            // auto rename the file...
            int count = 2;

            String fileExitWithoutExt = getFileNameWithoutExtension(filename);
            String ext = getFileExtension(filename);

            File newFileInfo;

            do {
                newFileInfo = new File(dirInfo, String.format("%s%d%s", fileExitWithoutExt, (count++), ext));
            } while (newFileInfo.exists());

            return newFileInfo.getCanonicalPath();
        }
        return filename;
    }

    public static String allocateFile(String filename, long filesize) throws IOException {
        File fileInfo = new File(filename);
        File dirInfo = new File(fileInfo.getParent());
        if (!dirInfo.exists()) {
            dirInfo.mkdirs();
        }

        RandomAccessFile file = new RandomAccessFile(filename, "rw");
        file.setLength(filesize);
        file.close();
        return filename;
    }

    public static void launchFile(String filename) throws IOException {
        Desktop.getDesktop().open(new File(filename));
    }

    public static void launchDirectory(String filename) throws IOException {
        File f = new File(filename);
        if (!f.isDirectory()) {
            f = f.getParentFile();
        }
        Desktop.getDesktop().open(f);
    }

    public static void main(String[] args) throws IOException {
        File f = new File("d:\\oh\\yeah\\wow.dat");
        /*if (f.exists()) {
        f.delete();
        }*/
        allocateFile(f.getCanonicalPath(), 200000L);
        launchFile("e:\\Movie\\help.flv");
        launchDirectory("e:\\Movie\\help.flv");
    }
}
